//
//  CCWebViewController.swift
//  SwiftStudy
//
//  Created by chang on 2018/3/12.
//  Copyright © 2018年 chang. All rights reserved.
//

import UIKit
import WebKit

class CCWebViewController: UIViewController {

    var webView : CCWebView!
    var backItem : UIBarButtonItem!
    var closeItem : UIBarButtonItem!
    var webUrl : NSString!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.isNavigationBarHidden = false
        self.view.backgroundColor = UIColor.defaultBackgroundColor
        self.automaticallyAdjustsScrollViewInsets = false
        self.navigationItem.title = "视频详情"

        webView = CCWebView.init(frame: CGRect.init(x: 0, y: self.navgationBarBottom, width: MAINSCREEN_WIDTH, height: MAINSCREEN_HEIGHT-self.navgationBarBottom))
        webView.delegate = self
        // 配置webView样式
        var config = WkwebViewConfig()
        config.isShowScrollIndicator = false
        config.isProgressHidden = false
        // 加载普通URL
        webView.webConfig = config
        webView.webloadType(self, .URLString(url: webUrl as String))
        
        /**
         // 加载本地URL
         config.scriptMessageHandlerArray = ["valueName"]
         webView.webConfig = config
         webView.delegate = self
         webView.webloadType(self, .HTMLName(name: "test"))
         */
        
        /**
        // POST加载
        let mobile = ""
        let pop = ""
        let auth = ""
        let param = ["mobile":"\(mobile)","pop":"\(pop)","auth":"\(auth)"];
        webView.webConfig = config
        webView.webloadType(self, .POST(url: "http://xxxxx", parameters: param))
        */
        
        self.view.addSubview(webView)
        
        self.navigationConfig()
    }
    
    func navigationConfig() {
        
        let backBtn = UIButton.init(type: .custom)
        backBtn.setImage(UIImage.init(named: "re_back"), for: .normal)
        backBtn.addTarget(self, action: #selector(backAction(sender:)), for: .touchUpInside)
        backItem = UIBarButtonItem.init(customView: backBtn)
        
        let closeBtn = UIButton.init(type: .custom)
        closeBtn.setImage(UIImage.init(named: "re_close"), for: .normal)
        closeBtn.addTarget(self, action: #selector(closeAction(sender:)), for: .touchUpInside)
        closeItem = UIBarButtonItem.init(customView: closeBtn)
        
        self.showLeftBarButtonItem()
        
        let freshBtn = UIButton.init(type: .custom)
        freshBtn.setImage(UIImage.init(named: "re_fresh"), for: .normal)
        freshBtn.addTarget(self, action: #selector(freshAction(sender:)), for: .touchUpInside)
        let freshItem = UIBarButtonItem.init(customView: freshBtn)
        
        self.navigationItem.rightBarButtonItem = freshItem
    }
    
    func showLeftBarButtonItem() {
        if webView.webView.canGoBack {
            self.navigationItem.leftBarButtonItems = [backItem,closeItem]
        }else{
            self.navigationItem.leftBarButtonItem = backItem
        }
    }
    
    @objc func backAction(sender: UIButton) {
        if webView.webView.canGoBack {
            webView.webView.goBack()
        }else{
            if self.navigationController?.topViewController == self {
                self.navigationController?.popViewController(animated: true)
            }else{
                self.dismiss(animated: true, completion: nil)
            }
        }
    }
    
    @objc func closeAction(sender: UIButton) {
        if self.navigationController?.topViewController == self {
            self.navigationController?.popViewController(animated: true)
        }else{
            self.dismiss(animated: true, completion: nil)
        }
    }
    
    @objc func freshAction(sender: UIButton) {
//        webView.reload()
        webView.webloadType(self, .URLString(url: webUrl as String))
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension CCWebViewController : CCWebViewDelegate{
    
    /// 页面开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    }
    
    /// 页面加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //执行JS方法获取导航栏标题
        webView.evaluateJavaScript("document.title", completionHandler: {
            [weak self] (aTitle, error) in
            self?.navigationItem.title = aTitle as? String
        })
        self.showLeftBarButtonItem()
        self.webUrl =  NSString.init(string: (webView.url?.absoluteString)!)
    }
    
    /// 跳转失败的时候调用
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    }
    
    /// 内容加载失败
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    }
    
    /**
     func webViewUserContentController(_ scriptMessageHandlerArray: [String], didReceive message: WKScriptMessage) {
     print(message.body)
     }
     */
}


